﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using StockMatch.Service;
using StockMatch.Service.Entity;
using StockMatch.WebSite.Models;
using Titan;

namespace StockMatch.WebSite.Controllers
{
    public class WeekWinController : StockControllerBase
    {
        public ActionResult Index(string param)
        {
            ViewBag.Menu = "weekwin";
            WeekWin weekWin = new WeekWin();
            if (!string.IsNullOrEmpty(param))
            {
                string[] ps = param.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
                weekWin.FirmCapital = decimal.Parse(ps[0].Split('=')[1]);
                weekWin.RiskMargin = int.Parse(ps[1].Split('=')[1]);
                weekWin.TotalTrade = decimal.Parse(ps[2].Split('=')[1]);
                weekWin.LossWarLine = decimal.Parse(ps[3].Split('=')[1]);
                weekWin.LossOpenLine = decimal.Parse(ps[4].Split('=')[1]);
                weekWin.ManageMoney = decimal.Parse(ps[5].Split('=')[1]);
                weekWin.StartTime = int.Parse(ps[6].Split('=')[1]);
                weekWin.Type = int.Parse(ps[7].Split('=')[1]);
            }
            else
            {
                weekWin.FirmCapital = 10000;
                weekWin.RiskMargin = 2000;
            }
            return View(weekWin);
        }
        public ActionResult Banner()
        {
            return View();
        }

        public ActionResult Scroll()
        {
            return View();
        }

        public ActionResult Confirm(WeekWin weekWin)
        {
            var result = MathProject.MathRiskMargin(weekWin.FirmCapital);
            
            weekWin.FirmCapital = weekWin.FirmCapital;
            weekWin.TotalTrade = weekWin.FirmCapital > 0 ? weekWin.FirmCapital + result.Principal : 0;
            weekWin.LossWarLine = result.Warning;
            weekWin.LossOpenLine = result.Open;
            weekWin.ManageMoney = result.Fee;
            if (CurrentUser != null)
            {
                User user = ServiceManager.UserService.GetUser(CurrentUser.UserId);
                ViewBag.BalanceAmount = user.BalanceAmount;
            }
            ViewBag.RiskMargin = result.Principal;
            ViewBag.Menu = "weekwin";
            return View(weekWin);
        }

        public ActionResult PostConfirm(WeekWin weekWin)
        {
            if (weekWin == null)
            {
                throw new ArgumentNullException("weekWin");
            }
            if (CurrentUser == null)
            {
                return Json(new { data = 2, message = "请先登录" });
            }
            WeekWinProject weekWinProject = new WeekWinProject();
            var result = MathProject.MathRiskMargin(weekWin.FirmCapital);
            weekWinProject.UserId = CurrentUser.UserId;
            weekWinProject.FirmCapital = weekWin.FirmCapital;//实盘资金
            weekWinProject.RiskMargin = result.Principal;//风险保证金
            weekWinProject.TotalTrade = weekWin.FirmCapital > 0 ? weekWin.FirmCapital + result.Principal : 0;//总操盘资金
            weekWinProject.LossWarLine = result.Warning;//亏损警告线
            weekWinProject.LossOpenLine = result.Open;//亏损平仓
            weekWinProject.ManageMoney = result.Fee;//账号管理费
            weekWinProject.FundTime = weekWin.FundTime;//资金使用期限
            weekWinProject.StartTime = weekWin.StartTime;
            DateTime nextDate = DateTime.Now.AddDays(1);
            weekWinProject.StartProjectTime = weekWinProject.StartTime == 0
                ? DateTime.Now
                : new DateTime(nextDate.Year, nextDate.Month, nextDate.Day, 9, 0, 0);//下个交易日
            weekWinProject.AddTime = DateTime.Now;
            weekWinProject.ProjectState = (int)ProjectStateEnum.CapitalVerification; ;//正在验资中
            weekWinProject.Proportion = 70;//盈利返回（盈利全归客户）

            User user = ServiceManager.UserService.GetUser(CurrentUser.UserId);
            if (user.BalanceAmount < weekWinProject.RiskMargin)
            {
                return Json(new { data = 3, message = "账户余额不足" });
            }
            if (ServiceManager.WeekWinProjectService.Insert(weekWinProject))
            {
                return Json(new { data = 1, message = "ok" });
            }
            return Json(new { data = 0, message = "提交方案失败" });
        }

        public ActionResult Seccess(int id)
        {
            WeekWinProject weekWinProject = ServiceManager.WeekWinProjectService.GetWeekWinProject(id);
            return View(weekWinProject);
        }

        public ActionResult Project(int id)
        {
            WeekWinProject weekWinProject = ServiceManager.WeekWinProjectService.GetWeekWinProject(id);
            if (weekWinProject == null)
            {
                return View("~/Views/WeekWin/Project404.cshtml");
            }

            #region 追加保证金记录
            QueryExpression query = new QueryExpression();
            query.EntityType = typeof(WeekWinProjectRiskMargin);
            query.Select(WeekWinProjectRiskMargin_.ALL);
            query.Where(WeekWinProjectRiskMargin_.ProjectId.TEqual(weekWinProject.ProjectId));
            query.OrderBy(WeekWinProjectRiskMargin_.AddTime.Asc);
            WeekWinProjectRiskMargins dayWinProjectRiskMargins = ServiceManager.WeekWinProjectRiskMarginService.GetProjectRiskMargins(query);
            ViewData["WeekWinProjectRiskMargin"] = dayWinProjectRiskMargins;
            ViewData["WeekWinProjectRiskMargin0"] = dayWinProjectRiskMargins.Items.Where(p => p.AddState == 1).ToList();
            #endregion
            return View(weekWinProject);
        }

        [HttpPost]
        public ActionResult AddRiskMargin(int projectId, int riskMargin, int type)
        {
            if (riskMargin < 100)
            {
                return Json(new { data = 0, message = "追加的保证金金额不能小于100元" });
            }
            if (CurrentUser == null)
            {
                return Json(new { data = 0, message = "请先登录" });
            }
            if (ServiceManager.UserService.GetUser(CurrentUser.UserId).BalanceAmount < riskMargin)
            {
                return Json(new { data = 0, message = "账户余额不足，请充值" });
            }
            int i = ServiceManager.WeekWinProjectService.AddRiskMargin(projectId, riskMargin, type);
            if (i == 2)
            {
                return Json(new { data = 0, message = "每天最多追加5次(包括取消次数)" });
            }
            if (i > 0)
            {
                return Json(new { data = 1, message = "申请追加保证金成功" });
            }
            return Json(new { data = 0, message = "申请追加保证金失败" });
        }
        
    }
}